package com.cilico.waterfall;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

public class ImageLoadUtil {
	// 图片缓存集合
	private HashMap<String, SoftReference<Drawable>> imageCache;
	private static boolean isLoad = true;

	public ImageLoadUtil() {
		imageCache = new HashMap<String, SoftReference<Drawable>>();
	}

	public void setUnLock(boolean isLoad) {
		this.isLoad = isLoad;
	}

	public void setOnLoadImageListener(final String tag,final String imageUrl, final LoadImageListener listener) {
		if (TextUtils.isEmpty(imageUrl)) {
			return;
		}
		if (imageCache.containsKey(tag)) {
			SoftReference<Drawable> softReference = imageCache.get(tag);
			// 获取指定图片的软引用
			Drawable drawable = softReference.get();
			// 若获取到高速缓存图片
			if (drawable != null) {
				listener.loadImage(drawable);
				return;
			}
		}
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				// 这样返回回去的图片可以直接设置imageView
				listener.loadImage((Drawable) message.obj);
			}
		};
		// 开一个线程下载图片
		new Thread() {
			@Override
			public void run() {
				try {
					if (imageUrl != null && !imageUrl.equals("") && !imageUrl.startsWith("local")) {
						Drawable drawable = ImageUtil.geRoundDrawableFromUrl(imageUrl, 10);
						if (drawable != null) {
							imageCache.put(tag, new SoftReference<Drawable>(drawable));
							Message message = handler.obtainMessage(0, drawable);
							handler.sendMessage(message);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	public interface LoadImageListener {
		public void loadImage(Drawable imageDrawable);
	}
}
